﻿using log4net.Config;
using Senparc.CO2NET;
using Senparc.CO2NET.RegisterServices;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.MP.Containers;
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Wei.App_Start;
using Wei.Attributes;
using Wei.Tool;
using Wei.Tool.baidu;

namespace Wei
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static string DirSiteFile;
        public static string DirParent;
        protected void Application_Start()
        {
            
            AreaRegistration.RegisterAllAreas();
          
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            //DirParent = new System.IO.DirectoryInfo(Server.MapPath("~/")).Parent.FullName + "\\";
            DirParent = Server.MapPath("~/");
            DirSiteFile = DirParent + "SiteFile\\";
            Log.LogWritePath = string.Format("{0}log\\{{0:yyyy-MM-dd}}.txt", DirSiteFile);
            //设置百度编辑器的配置路径
            UeditorUploadHandlerTool.FileDir = DirSiteFile;
            UeditorConfigTool.UeditorConfigPath = Server.MapPath("~/Content/ueditor1.4.3.3/config.json");
            Application["online"] = 0;

            //log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(Server.MapPath("~/Web.config")));
            //应用程序启动时，自动加载配置log4Net  
            XmlConfigurator.Configure();

            /* CO2NET 全局注册开始
         * 建议按照以下顺序进行注册
         */

            //设置全局 Debug 状态
            var isGLobalDebug = true;
            var senparcSetting = SenparcSetting.BuildFromWebConfig(isGLobalDebug);

            //CO2NET 全局注册，必须！！
            IRegisterService register = RegisterService.Start(senparcSetting)
                                          .UseSenparcGlobal(false, null);

            /* 微信配置开始
             * 建议按照以下顺序进行注册
             */

            //设置微信 Debug 状态
            var isWeixinDebug = true;
            var senparcWeixinSetting = SenparcWeixinSetting.BuildFromWebConfig(isWeixinDebug);

            //微信全局注册，必须！！
            register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting);
            AccessTokenContainer.Register(Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId, Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppSecret);//全局只需注册一次，例如可以放在Global的Application_Start()方法中。

            //AutoTaskAttribute.RegisterTask();//注册定时任务
            //Models.初始化.Create_Menu();
        }

        //添加Application_End 方法,解决IIS应用程序池自动回收的问题
        protected void Application_End()
        {
            Thread.Sleep(1000);
            //这里设置你的web地址，可以随便指向你的任意一个aspx页面甚至不存在的页面，目的是要激发Application_Start <br>　　　　　　　
            //我这里是一个验证token的地址。
            //string url = System.Configuration.ConfigurationManager.AppSettings["tokenurl"];
            string url = "http://localhost:62716/home/hehe";
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流
        }

        protected void Application_Error()
        {
            Exception lastError = Server.GetLastError();
            if (lastError != null)
            {
                //异常信息
                string strExceptionMessage = string.Empty;

                //对HTTP 404做额外处理，其他错误全部当成500服务器错误
                HttpException httpError = lastError as HttpException;
                if (httpError != null)
                {
                    //获取错误代码
                    int httpCode = httpError.GetHttpCode();
                    strExceptionMessage = httpError.Message;
                    if (httpCode == 400 || httpCode == 404)
                    {
                        Response.StatusCode = 404;
                        //跳转到指定的静态404信息页面，根据需求自己更改URL
                        Response.WriteFile("~/404.html");
                        Server.ClearError();
                        return;
                    }
                }

                strExceptionMessage = lastError.Message;

                /*-----------------------------------------------------
                 * 此处代码可根据需求进行日志记录，或者处理其他业务流程
                 * ---------------------------------------------------*/
                LogHelper.WriteLog(typeof(LogAttribute), new GetRequestInfo().GetInfo(HttpContext.Current.Request, HttpContext.Current.Response), lastError);
                /*
                 * 跳转到指定的http 500错误信息页面
                 * 跳转到静态页面一定要用Response.WriteFile方法                 
                 */
                Response.StatusCode = 500;
                Response.WriteFile("~/500.html");

                //一定要调用Server.ClearError()否则会触发错误详情页（就是黄页）
                Server.ClearError();
            }
        }

        protected void Session_Start()//进行连接  
        {
            //Session.Timeout = 1;
            Application.Lock();//加锁：防并发  
            Application["online"] = (int)Application["online"] + 1;    //在线人数+1  
            Application.UnLock();//解锁  
        }
        /// <summary>
        /// session结束事件，触发事件有session过期或终止session进入
        /// </summary>
        protected void Session_End()
        {
            Application.Lock();
            Application["online"] = (int)Application["online"] - 1;
            Application.UnLock();
        }
    }
}
